package com.cjack.frenchexcel.controller;

import com.alibaba.fastjson.JSONObject;
import com.cjack.frenchexcel.config.AjaxResult;
import com.cjack.frenchexcel.config.CommonConfig;
import com.cjack.frenchexcel.config.ErrorCodeDefine;
import com.cjack.frenchexcel.config.LayPage;
import com.cjack.frenchexcel.dao.CooperativeNumberDao;
import com.cjack.frenchexcel.dao.UserAdminDao;
import com.cjack.frenchexcel.exception.BankCardNotExsitException;
import com.cjack.frenchexcel.exception.CommonException;
import com.cjack.frenchexcel.exception.DateErrorException;
import com.cjack.frenchexcel.model.ConsumerRecordConditionModel;
import com.cjack.frenchexcel.model.ConsumerRecordModel;
import com.cjack.frenchexcel.service.ConsumerRecordService;
import com.cjack.frenchexcel.service.UserAdminService;
import com.cjack.frenchexcel.table.ConsumerRecordTable;
import com.cjack.frenchexcel.table.CooperativeNumberTable;
import com.cjack.frenchexcel.table.MooncardTable;
import com.cjack.frenchexcel.util.ModelUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/consumer")
public class ConsumerExcelEndpoint extends BaseEndpoint {

    @Autowired
    ConsumerRecordService service;
    @Autowired
    CooperativeNumberDao cooperativeNumberDao;
    @Autowired
    UserAdminDao userAdminDao;

    /**
     * 导出excel，分两步走，先生成excel放到对应的目录，再返回生成的excel的地址给浏览器端
     */
    @RequestMapping(value = "/exportAsExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult exportAsExcel(HttpSession session, ConsumerRecordConditionModel condition) {
        Object loginUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        condition.setLoginUserId((Long) loginUserId);
        JSONObject json = service.exportAsExcel(condition);
        return AjaxResult.SUCCESS(json);
    }

    /**
     * 导出银行流水excel，分两步走，先生成excel放到对应的目录，再返回生成的excel的地址给浏览器端
     */
    @RequestMapping(value = "/exportBankStatement", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult exportBankStatement(HttpSession session, ConsumerRecordConditionModel condition) {
        Object loginUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        condition.setLoginUserId((Long) loginUserId);
        JSONObject json = service.exportBankStatement(condition);
        return AjaxResult.SUCCESS(json);
    }

    /**
     * 导出excel，分两步走，先生成excel放到对应的目录，再返回生成的excel的地址给浏览器端
     *
     * @param condition
     * @return
     */
    @RequestMapping(value = "/exportInvoice", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult exportInvoice(HttpSession session, ConsumerRecordConditionModel condition) {
        Object loginUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        condition.setLoginUserId((Long) loginUserId);
        JSONObject json = service.exportInvoice(condition);
        return AjaxResult.SUCCESS(json);
    }

    /**
     * 从excel里面导入数据，分成两步来弄
     * 1、先调用upload接口上传excel文件到服务器
     * 2、用第一步上传返回的excel地址调用此接口
     * 从excel导入数据
     *
     * @param filePath excel的浏览器端访问路径
     * @return
     */
    @RequestMapping(value = "/importFromExcel2", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult importFromExcel2(@RequestParam("filePath") String filePath, HttpSession session) {
        Object loginUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        if (StringUtils.isEmpty(filePath)) {
            throw new CommonException(ErrorCodeDefine.INTERFACE_COMMON_ERROR, "filePath不能为空");
        }
        //注意pageDate里面的页数是从0开始计算的
        JSONObject json = service.importFromExcel2(filePath, (Long) loginUserId);
        //返回重复的数据
        return AjaxResult.SUCCESS(json);
    }

    /**
     * 列表
     *
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult list(HttpSession session, LayPage layPage, Integer red, ConsumerRecordConditionModel condition) {

        try {
            Object loginUserId = session.getAttribute(CommonConfig.SESSION_NAME);
            condition.setLoginUserId((Long) loginUserId);
            Page<ConsumerRecordTable> resultPage = service.list(layPage, condition);
            List<ConsumerRecordModel> datas = new ArrayList<>();
            for (ConsumerRecordTable table : resultPage.getContent()) {
                ConsumerRecordModel model = ModelUtils.copySignModel(table, ConsumerRecordModel.class);
                if (StringUtils.isEmpty(model.getJobNumber())) {
                    if (userAdminDao.findByJobNumber(model.getCollaborateur()) != null) {
                        model.setJobNumber(model.getCollaborateur());
                    } else {
                        model.setJobNumber("NOT_FOUND_USER");
                    }
                }
                //合作商数据 condition 合作商简名+员工编号
                CooperativeNumberTable exsits = cooperativeNumberDao.getByNameAndJobNumber(model.getFournisseur(), model.getJobNumber());
                if (exsits != null) {
                    model.setCooperativeNumber(exsits.getNumber());
                    model.setCooperativeSimpleName(exsits.getName());
                }
                //这里去掉负号
                model.setMontantTTC(String.valueOf((Double.valueOf(model.getMontantTTC()).doubleValue())));
                datas.add(model);
            }

            if (red != null && red == 1) {
                datas = datas.stream().filter(item-> Objects.isNull(item.getCooperativeSimpleName())).collect(Collectors.toList());
            }

            layPage.setData(datas);
            layPage.setCount(Long.valueOf(resultPage.getTotalElements()).intValue());
            return AjaxResult.SUCCESS(layPage);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    /**
     * 列表
     *
     * @return
     */
    @RequestMapping(value = "/listForCloudDisk", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult listForCloudDisk(HttpSession session, LayPage layPage, ConsumerRecordConditionModel condition) {

        try {
            layPage.setPage(1);
            layPage.setLimit(1000);
            Page<ConsumerRecordTable> resultPage = service.list(layPage, condition);
            List<ConsumerRecordModel> datas = new ArrayList<>();
            for (ConsumerRecordTable table : resultPage.getContent()) {
                ConsumerRecordModel model = ModelUtils.copySignModel(table, ConsumerRecordModel.class);
                if (StringUtils.isEmpty(model.getFournisseur())) {
                    continue;
                }
                if (!StringUtils.isEmpty(model.getInvoice())) {
                    continue;
                }
                if (StringUtils.isEmpty(model.getJobNumber())) {
                    if (userAdminDao.findByJobNumber(model.getCollaborateur()) != null) {
                        model.setJobNumber(model.getCollaborateur());
                    } else {
                        model.setJobNumber("NOT_FOUND_USER");
                    }
                }
                List<CooperativeNumberTable> exsits = cooperativeNumberDao.getByName(model.getFournisseur());
                if (CollectionUtils.isNotEmpty(exsits)) {
                    CooperativeNumberTable cooperativeNumberTable = exsits.get(0);
                    model.setCooperativeNumber(cooperativeNumberTable.getNumber());
                    model.setCooperativeSimpleName(cooperativeNumberTable.getName());
                }
                model.setMontantTTC(model.getMontantTTC());
                datas.add(model);
            }
            layPage.setData(datas);
            layPage.setCount(Long.valueOf(resultPage.getTotalElements()).intValue());
            return AjaxResult.SUCCESS(layPage);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    /**
     * mooncard列表
     *
     * @return
     */
    @RequestMapping(value = "/listForMooncard", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult listForMooncard(LayPage layPage) {

        try {
            Page<MooncardTable> resultPage = service.listForMooncard(layPage);
            List<ConsumerRecordModel> datas = new ArrayList<>();
            for (MooncardTable table : resultPage.getContent()) {
                ConsumerRecordModel model = ModelUtils.copySignModel(table, ConsumerRecordModel.class);
                model.setJobNumber(model.getCollaborateur());
                datas.add(model);
            }
            layPage.setData(datas);
            layPage.setCount(Long.valueOf(resultPage.getTotalElements()).intValue());
            return AjaxResult.SUCCESS(layPage);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    /**
     * 根据id获取下一条待审核的数据
     *
     * @return
     */
    @RequestMapping(value = "/getLastById", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult getLastById(Long id) {
        try {
            return AjaxResult.SUCCESS(service.getLastById(id));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    /**
     * 新增
     *
     * @return
     */
    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addOrUpdate(ConsumerRecordModel model) {
        try {
            if (isAdd(model.getId())) {
                model.setCreateTime(new Date());
            }
            model.setUpdateTime(new Date());
            service.add(model);
            return AjaxResult.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    /**
     * 新增
     *
     * @return
     */
    @RequestMapping(value = "/editCooperative", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult editCooperative(ConsumerRecordModel model) {
        try {
            service.editCooperative(model);
            return AjaxResult.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    /**
     * 合并数据
     *
     * @return
     */
    @RequestMapping(value = "/merge", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult merge(@RequestParam("ids") String ids) {
        try {

            service.merge(ids);
            return AjaxResult.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    /**
     * 拆分数据
     *
     * @return
     */
    @RequestMapping(value = "/partition", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult partition(@RequestParam("id") Long id,
                                @RequestParam("moneyOne") String moneyOne,
                                @RequestParam("moneyTwo") String moneyTwo) {
        try {
            service.partition(id, moneyOne, moneyTwo);
            return AjaxResult.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    /**
     * 删除
     *
     * @return
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult del(@RequestParam("ids") String ids) {
        try {
            service.del(ids);
            return AjaxResult.SUCCESS("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }
}
